package com.budwk.app.miniapp.services.impl;

import com.budwk.app.miniapp.models.dto.SysDictDataQueryDTO;
import com.budwk.app.miniapp.models.*;
import com.budwk.app.miniapp.services.*;
import com.budwk.app.miniapp.models.vo.EventScheduleDetailVO;
import com.budwk.starter.database.service.BaseServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.lang.StringUtils;
import org.nutz.aop.interceptor.async.Async;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.random.R;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@IocBean(args = {"refer:dao"})
public class WxeventscheduleServiceImpl extends BaseServiceImpl<WxEventSchedule> implements WxeventscheduleService {
    public WxeventscheduleServiceImpl(Dao dao) {
        super(dao);
    }

    @Inject
    private DictService dictService;

    @Inject
    WxSpiderVolunteerTeamService wxSpiderVolunteerTeamService;

    @Inject
    private WxeventService wxeventService;

    @Inject
    private SysdictdataService sysdictdataService;

    /*
     * 根据evenId更新schedule表删除状态信息
     * */
    @Override
    @Aop(TransAop.READ_COMMITTED)
    public void updateDelFlagByEventId(String id) {
        dao().execute(Sqls.create("update wx_event_schedule set delflag = true where event_id = @eventId").setParam("eventId", id));
    }

    /**
     * 根据事件的类型判得到相应的求助信息
     *
     * @param bo 主要得到相应的事件类型
     * @return 结果
     */
    @Override
    public List<EventScheduleDetailVO> createEventContentByEventType(WxEvent bo) {

        List<EventScheduleDetailVO> contentStrList = Lists.newArrayList();

        if (StringUtils.isBlank(bo.getEventType())) return contentStrList;

        // 求助类型的情况 在下面的代码中 do街道办 po派出所 hp医院 vt志愿者
        if (bo.getEventType().equals("natural_disaster")) {
            String eventContentType = bo.getEventContentType();   // 这个是内容类型code

            List<SysDictData> helpContentTypeGroupList = dictService.getSysDictDataList(new SysDictDataQueryDTO("help_content_type_group", null, null));
            Map<String, SysDictData> helpContentTypeGroupMap = helpContentTypeGroupList.stream().collect(Collectors.toMap(SysDictData::getDictValue, item -> item));
            List<SysDictData> groupSubList = Lists.newArrayList();
            List<String> helpContentTypeStrList = Lists.newArrayList();

            if (helpContentTypeGroupMap.containsKey(eventContentType)) {
                SysDictData groupDictData = helpContentTypeGroupMap.get(eventContentType);
                groupSubList = dictService.getSysDictDataList(new SysDictDataQueryDTO("help_content_type", groupDictData.getDictCode(), null));
                helpContentTypeStrList = groupSubList.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());
            }

            // wzy 2023-5-6 第二次大变动 这个时候因为用户选择的求助类型有大类和小类区分，所以先用大类进行查询筛选
            // 使用直接比较的方式判断相应的推送
            if (eventContentType.equals("life_transportation_help_need")) {
                // 生活/出行有困难需要帮助 推送 街道办 志愿者
                EventScheduleDetailVO doVO = getEventContentByEventType(bo, 1);
                if (doVO != null) contentStrList.add(doVO);

                EventScheduleDetailVO vtVO = getEventContentByEventType(bo, 0, helpContentTypeStrList);

                if (vtVO != null) contentStrList.add(vtVO);
            }

            if (eventContentType.equals("volunteers_need")) {
                // 需要社区服务志愿者 推送 街道办 志愿者团队团队
                EventScheduleDetailVO doVO = getEventContentByEventType(bo, 1);
                if (doVO != null) contentStrList.add(doVO);

                EventScheduleDetailVO vtVO = getEventContentByEventType(bo, 0, helpContentTypeStrList);
                if (vtVO != null) contentStrList.add(vtVO);
            }

            if (eventContentType.equals("health_service_need")) {
                // 需要医疗卫生服务 推送 社区医院 志愿者团队
                EventScheduleDetailVO teamOfHospital = getEventContentByEventType(bo, 2);
                if (teamOfHospital != null) contentStrList.add(teamOfHospital);

                EventScheduleDetailVO vtVO = getEventContentByEventType(bo, 0, helpContentTypeStrList);
                if (vtVO != null) contentStrList.add(vtVO);
            }

            if (eventContentType.equals("legal_advice_need")) {
                // 需要法律咨询、援助 推送 志愿者团队
                EventScheduleDetailVO vtVO = getEventContentByEventType(bo, 0, helpContentTypeStrList);
                if (vtVO != null) contentStrList.add(vtVO);
            }

            if (eventContentType.equals("tax_declaration_need")) {
                // 需要纳税申报咨询服务 推送 志愿者团队
                EventScheduleDetailVO vtVO = getEventContentByEventType(bo, 0, helpContentTypeStrList);
                if (vtVO != null) contentStrList.add(vtVO);
            }

            if (eventContentType.equals("assist_government_need")) {
                // 需要协助居民办理政务服务的志愿者 推送 街道办 派出所
                EventScheduleDetailVO doVO = getEventContentByEventType(bo, 1);
                if (doVO != null) contentStrList.add(doVO);

                EventScheduleDetailVO poVO = getEventContentByEventType(bo, 3);
                if (poVO != null) contentStrList.add(poVO);

            }

            if (eventContentType.equals("assistance_emergency_need")) {
                // 遇到紧急情况需要救助 推送 派出所 志愿者团队
                EventScheduleDetailVO poVO = getEventContentByEventType(bo, 3);
                if (poVO != null) contentStrList.add(poVO);

                EventScheduleDetailVO vtVO = getEventContentByEventType(bo, 0, helpContentTypeStrList);
                if (vtVO != null) contentStrList.add(vtVO);
            }

            // if (eventContentType.equals("other_requirement_need")) {
            //    // 其他 因为其他的类型需要选择小类，所以这种情况目前用不到
            // }

            if (contentStrList.size() > 0) return contentStrList;

            // 推送街道办 志愿者团队
            Set<String> DOAndVT = Sets.newHashSet("社区服务", "环境保护", "文化艺术", "文明风尚", "体育健身", "旅游服务", "关爱特殊群体", "大型活动", "疫情防控", "家庭教育", "垃圾分类", "为儿童服务", "为老人服务", "扶贫减贫", "志愿消防", "志愿服务");

            // 志愿者
            Set<String> VT = Sets.newHashSet("科技科普", "支教助学", "海外志愿服务", "税收服务", "其他");

            // 街道办 医院 志愿者团队
            Set<String> DOAndHPAndVT = Sets.newHashSet("卫生健康");

            // 派出所 志愿者
            Set<String> POAndVT = Sets.newHashSet("法律服务", "平安综治", "交通引导", "应急救援", "禁毒宣传", "网络文明", "海防志愿者");

            // 街道办 派出所 志愿者
            Set<String> DOAndPOAndVT = Sets.newHashSet("救助帮扶");

            // 街道办 派出所
            Set<String> DOAndPO = Sets.newHashSet("便民服务");

            // 从redis中或者数据库中获取对应的字段表 根据前端传入的code得到相应的名称
            SysDictData sysDictData= sysdictdataService.fetch(Cnd.where(SysDictData::getDictValue,"=",eventContentType));
            String eventContentTypeStr = sysDictData.getDictLabel();

            // 根据 省 市 区 街道 找到相应的街道办事处
            // 目前找到一个最近的志愿者/机构的方法为 根据省市区找到数据，然后再根据经纬度计算最近的

            // 下面方法中的institutionType暂时在这个方法中写死使用，后续如果有需要再进行写枚举使用
            if (DOAndVT.contains(eventContentTypeStr)) {
                EventScheduleDetailVO doVO = getEventContentByEventType(bo, 1);
                if (doVO != null) contentStrList.add(doVO);

                EventScheduleDetailVO vtVO = getEventContentByEventType(bo, 0, eventContentTypeStr);
                if (vtVO != null) contentStrList.add(vtVO);
            }


            if (VT.contains(eventContentTypeStr)) {
                EventScheduleDetailVO vtVO = getEventContentByEventType(bo, 0, eventContentTypeStr);
                if (vtVO != null) contentStrList.add(vtVO);
            }

            if (DOAndHPAndVT.contains(eventContentTypeStr)) {
                EventScheduleDetailVO doVO = getEventContentByEventType(bo, 1);
                if (doVO != null) contentStrList.add(doVO);

                EventScheduleDetailVO teamOfHospital = getEventContentByEventType(bo, 2);
                if (teamOfHospital != null) contentStrList.add(teamOfHospital);

                EventScheduleDetailVO vtVO = getEventContentByEventType(bo, 0, eventContentTypeStr);
                if (vtVO != null) contentStrList.add(vtVO);
            }

            if (POAndVT.contains(eventContentTypeStr)) {
                EventScheduleDetailVO poVO = getEventContentByEventType(bo, 3);
                if (poVO != null) contentStrList.add(poVO);

                EventScheduleDetailVO vtVO = getEventContentByEventType(bo, 0, eventContentTypeStr);
                if (vtVO != null) contentStrList.add(vtVO);
            }

            if (DOAndPOAndVT.contains(eventContentTypeStr)) {
                EventScheduleDetailVO doVO = getEventContentByEventType(bo, 1);
                if (doVO != null) contentStrList.add(doVO);

                EventScheduleDetailVO poVO = getEventContentByEventType(bo, 3);
                if (poVO != null) contentStrList.add(poVO);

                EventScheduleDetailVO vtVO = getEventContentByEventType(bo, 0, eventContentTypeStr);
                if (vtVO != null) contentStrList.add(vtVO);
            }

            if (DOAndPO.contains(eventContentTypeStr)) {
                EventScheduleDetailVO doVO = getEventContentByEventType(bo, 1);
                if (doVO != null) contentStrList.add(doVO);

                EventScheduleDetailVO poVO = getEventContentByEventType(bo, 3);
                if (poVO != null) contentStrList.add(poVO);
            }
        }

        // 求救信息
        if (bo.getEventType().equals("emergency_events")) {
            EventScheduleDetailVO teamOfHospital = getEventContentByEventType(bo, 2);
            if (teamOfHospital != null) contentStrList.add(teamOfHospital);

            EventScheduleDetailVO teamOfPolice = getEventContentByEventType(bo, 3);
            if (teamOfPolice != null) contentStrList.add(teamOfPolice);
        }

        return contentStrList;
    }

    @Override
    public List<EventScheduleDetailVO> listEventScheduleDetail(String eventId) {
        Cnd cnd = Cnd.NEW();
        cnd.and("even_id", "=", eventId);
        cnd.orderBy("even_id", "desc");
        List<WxEventSchedule> wxEventScheduleList = this.query(cnd);

        List<EventScheduleDetailVO> resultList = Lists.newArrayList();
        for (WxEventSchedule wxEventSchedule : wxEventScheduleList) {
            EventScheduleDetailVO scheduleDetailVO = new EventScheduleDetailVO();
            //标题
            scheduleDetailVO.setTitle(wxEventSchedule.getEventContent());
            // 时间
            scheduleDetailVO.setEventScheduleTime(wxEventSchedule.getEventTime());
            // 处理内容
            String eventContent = wxEventSchedule.getEventContent();
            String eventContentJson = wxEventSchedule.getEventContentJson();
            if (StringUtils.isNotBlank(eventContentJson)) {
                String[] split = eventContentJson.split("--");
                EventScheduleDetailVO.VolunteerTeamVO volunteerTeamVO = new EventScheduleDetailVO.VolunteerTeamVO();
                volunteerTeamVO.setTeamName(split[0]);
                volunteerTeamVO.setContactPhone(split[1]);
                volunteerTeamVO.setAddress(split[2]);

                scheduleDetailVO.setVolunteerTeamInfo(volunteerTeamVO);
                scheduleDetailVO.setTitle(scheduleDetailVO.getTitle());

                scheduleDetailVO.setRemark("以上信息祥云AI为您提供");

                resultList.add(scheduleDetailVO);
            }
        }
        return resultList;
    }


    /**
     * 新增事件
     */
    @Override
    public void insertWxEventScheduleService(WxEvent bo) {
        try {
            //添加人等
            Date day = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            WxEventSchedule wxEventScheduleBo = new WxEventSchedule();
            wxEventScheduleBo.setId(R.UU32());
            wxEventScheduleBo.setEventId(bo.getId());
            wxEventScheduleBo.setEventTime(sdf.format(day));
            wxEventScheduleBo.setEventType(bo.getEventType());
            wxEventScheduleBo.setEventStatus(bo.getEventStatus());

            // wzy 2023-4-21 因为涉及到志愿者锁单的情况
            boolean finalInsertFlag = true;
            if (bo.getCompleteType() != null && bo.getCompleteType().equals("Y") && bo.getEventType().equals("natural_disaster")) {
                wxEventScheduleBo.setEventContent("感谢您对祥云志愿者的支持");
            }
            if (bo.getCompleteType() != null && bo.getCompleteType().equals("N") && bo.getEventType().equals("natural_disaster")) {
                wxEventScheduleBo.setEventContent("很遗憾志愿者未能为您提供帮助，您可以点击重新发布祥云AI将再次为您寻找志愿者");
            }
            //完成
            if (bo.getCompleteType() != null && bo.getCompleteType().equals("Y") && bo.getEventType().equals("emergency_events")) {
                wxEventScheduleBo.setEventContent("感谢您对救援人员的支持");
            }
            if (bo.getCompleteType() != null && bo.getCompleteType().equals("N") && bo.getEventType().equals("emergency_events")) {
                wxEventScheduleBo.setEventContent("我们将再次通知救援人员");
            }
            //取消
            if (bo.getEventStatus().equals("canceled") && bo.getEventType().equals("natural_disaster"))//求助
            {
                wxEventScheduleBo.setEventContent("您已经取消本次求助，感谢您对祥云AI的信任");
            }
            if (bo.getEventStatus().equals("canceled") && bo.getEventType().equals("emergency_events")) //求救
            {
                wxEventScheduleBo.setEventContent("您已经取消本次求救，感谢您对祥云AI的信任");
            }
            // pending_evaluation  再次接单
            if (bo.getEventStatus().equals("pending_evaluation") && bo.getEventType().equals("natural_disaster")) { // 求助
                if (bo.getVolunteerPhone() != null && bo.getVolunteerPhone().length() >= 11) {
                    wxEventScheduleBo.setEventContent("尾号" + bo.getVolunteerPhone().substring(7, 11) + "的祥云志愿者已接受你的求助，请保持手机畅通，等待志愿者电话");
                    // wzy 2023-5-4 当志愿者接单的时候需要将志愿者接单的事件写入事件
                    WxEvent wxEvent = wxeventService.fetch(wxEventScheduleBo.getEventId());
                    if (wxEvent == null) return;
                    wxEvent.setVolunteerOrdertime(new Date());
                    update(wxEvent);
                    insertiWxEventScheduleServiceWait(bo);
                }
            }
            if (bo.getEventStatus().equals("pending_evaluation") && bo.getEventType().equals("emergency_events")) { //求救
                wxEventScheduleBo.setEventContent("救援人员将为您提供服务，请保持手机畅通");
                insertiWxEventScheduleServiceWait(bo);
            }
            // pending_evaluation 重新下单的时候需要人工审核
            if (bo.getEventStatus().equals("N") && bo.getEventType().equals("natural_disaster")) { //求助
                wxEventScheduleBo.setEventContent("您的求助信息正在人工审核中，请耐心等待");
            }
            if (bo.getEventStatus().equals("N") && bo.getEventType().equals("emergency_events")) { //求救
                wxEventScheduleBo.setEventContent("您的求救信息正在人工审核中，请耐心等待");
            }
            //重新点击，审核通过
            if (bo.getEventStatus().equals("Y") && bo.getEventType().equals("natural_disaster")) { //求助
                wxEventScheduleBo.setEventContent("您的求助信息已通过审核，祥云AI正在为您找寻志愿者");
            }
            if (bo.getEventStatus().equals("Y") && bo.getEventType().equals("emergency_events")) { //求救
                wxEventScheduleBo.setEventContent("您的求救信息已通过审核，祥云AI正在为您找寻专业救援人员");
            }
            //“信息状态”为“已完成”时
            //if (bo.getEventStatus().equals("finished") && bo.getVolunteerWhetherHelp().equals("Y") && bo.getEventType().equals("natural_disaster")) { //求助
            //    wxEventScheduleBo.setEventContent("感谢您对祥云志愿者的支持");
            // }
            if (bo.getEventStatus().equals("finished") && bo.getEventType().equals("natural_disaster")) { //求助
                bo.setVolunteerWhetherHelp("Y");
                wxEventScheduleBo.setEventContent("感谢您对祥云志愿者的支持");
            }
            if (bo.getEventStatus().equals("finished") && bo.getVolunteerWhetherHelp().equals("N") && bo.getEventType().equals("natural_disaster")) { //求助
                wxEventScheduleBo.setEventContent("很遗憾志愿者未能为您提供帮助，您可以点击重新发布祥云AI将再次为您寻找志愿者");
            }
            // if (bo.getEventStatus().equals("finished") && bo.getVolunteerWhetherHelp().equals("Y") && bo.getEventType().equals("emergency_events")) { //求救
            //     wxEventScheduleBo.setEventContent("感谢您对救援人员的支持");
            // }
            // if (bo.getEventStatus().equals("finished") && bo.getVolunteerWhetherHelp().equals("N") && bo.getEventType().equals("emergency_events")) { //求救
            //    wxEventScheduleBo.setEventContent("我们将再次通知救援人员");
            // }
            if (bo.getEventStatus().equals("finished") && bo.getEventType().equals("emergency_events")) { //求救
                    bo.setVolunteerWhetherHelp("Y");
                wxEventScheduleBo.setEventContent("感谢您对救援人员的支持");
            }
            if (StringUtils.isNotBlank(wxEventScheduleBo.getEventContent())) {
                insert(wxEventScheduleBo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 帮助 等5分钟
     * 6-1-2.当前时间减去“待帮助状态改变时间"大于五分钟时，将“信息状态”、“当前时间”以及文案“志愿者是否已为您提供帮助，是或否”推送到小程序；
     */
    @Async
    public void insertiWxEventScheduleServiceWait(WxEvent bo) {
        try {
            try {
                Thread.sleep(5 * 60 * 1000); // 5 分钟等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //添加人等
            Date day = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            WxEventSchedule wxEventScheduleBo = new WxEventSchedule();
            wxEventScheduleBo.setEventId(bo.getId());
            wxEventScheduleBo.setEventTime(sdf.format(day));
            wxEventScheduleBo.setEventStatus(bo.getEventType());
            //pending_evaluation  接单
            if (bo.getEventStatus().equals("pending_evaluation") && bo.getEventType().equals("natural_disaster"))//求助
            {
                wxEventScheduleBo.setEventContent("志愿者是否已为您提供帮助，是或否");
            }
            if (bo.getEventStatus().equals("pending_evaluation") && bo.getEventType().equals("emergency_events")) //求救
            {
                wxEventScheduleBo.setEventContent("救援人员是否已联系您，是或否");
            }
            insert(wxEventScheduleBo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //---------------------------------------------------------------
    //下面是一些私有的方法
    //---------------------------------------------------------------

    private EventScheduleDetailVO getEventContentByEventType(WxEvent bo, int institutionType, List<
            String> eventContentTypeList) {
        return getEventContentByEventType(bo, institutionType, "", eventContentTypeList);
    }

    private EventScheduleDetailVO getEventContentByEventType(WxEvent bo, int institutionType, String
            eventContentTypeStr) {
        return getEventContentByEventType(bo, institutionType, eventContentTypeStr, null);
    }

    private EventScheduleDetailVO getEventContentByEventType(WxEvent bo, int institutionType) {
        return getEventContentByEventType(bo, institutionType, "", null);
    }


    private EventScheduleDetailVO getEventContentByEventType(WxEvent bo, int institutionType, String
            eventContentTypeStr, List<String> eventContentTypeList) {

        String institutionStr = "";
        switch (institutionType) {
            case 0:
                institutionStr = "志愿者团队";
                break;
            case 1:
                institutionStr = "街道办事处";
                break;
            case 2:
                institutionStr = "医院";
                break;
            case 3:
                institutionStr = "派出所";
                break;
        }

        String province = bo.getEventProvince();    // 省
        String city = bo.getEventCity();            // 市
        String district = bo.getEventDistrict();    // 区
        String street = bo.getEventStreet();        // 街道 只有公安局的时候会用到
        Double latitude = bo.getLatitude();         // 纬度
        Double longitude = bo.getLongitude();       // 经度

        // type是为了区分街道办事处 或者 医院 或者 派出所
        // 我们现在直接使用明文来进行操作 1办事处 2医院 3派出所
        WxSpiderTeamByPlaceQueryBO queryBO = new WxSpiderTeamByPlaceQueryBO();
        queryBO.setProvince(province);
        queryBO.setCity(city);
        queryBO.setDistrict(district);
        queryBO.setStreet(street);
        queryBO.setLatitude(latitude);
        queryBO.setLongitude(longitude);
        queryBO.setInstitutionType(institutionType);
        queryBO.setEventContentTypeStr(eventContentTypeStr);
        queryBO.setEventContentTypeList(eventContentTypeList);
        Sql sql = null;
        sql = Sqls.create(queryVolunteerTeamSqlBuiler(queryBO));
        List<WxSpiderVolunteerTeam> volunteerTeamList = wxSpiderVolunteerTeamService.listEntity(sql);

        // 如果是查询公安局 并且是城区() 并且没有根据街道查找到 就往上一级进行查找
        if (street.contains("街道")) {
            if (3 == institutionType && volunteerTeamList.size() == 0) {
                queryBO.setStreet("*");
                sql = Sqls.create(queryVolunteerTeamSqlBuiler(queryBO));
                volunteerTeamList = wxSpiderVolunteerTeamService.query(sql.getString());
            }
        }

        // 如果查询到了志愿者机构信息 则取第一个
        if (volunteerTeamList.size() > 0) {
            EventScheduleDetailVO eventScheduleDetailVO = new EventScheduleDetailVO();
            eventScheduleDetailVO.setTitle("离你最近的" + institutionStr);

            WxSpiderVolunteerTeam volunteerTeam = volunteerTeamList.get(0);
            String teamName = volunteerTeam.getTeamname();

            // 地址
            String teamAddress = volunteerTeam.getDetailedaddress();
            if (StringUtils.isBlank(teamAddress)) teamAddress = volunteerTeam.getAddress();
            if (StringUtils.isBlank(teamAddress)) return null;

            // 电话
            String teamPhone = volunteerTeam.getLandlinephone();
            if (StringUtils.isBlank(teamPhone)) teamPhone = volunteerTeam.getContactphone();
            if (StringUtils.isBlank(teamPhone)) return null;

            EventScheduleDetailVO.VolunteerTeamVO volunteerTeamVO = new EventScheduleDetailVO.VolunteerTeamVO();
            // volunteerTeamVO.setTeamTypeStr(institutionStr);
            volunteerTeamVO.setTeamName(teamName);
            volunteerTeamVO.setAddress(teamAddress);
            volunteerTeamVO.setContactPhone(teamPhone);

            eventScheduleDetailVO.setVolunteerTeamInfo(volunteerTeamVO);

            return eventScheduleDetailVO;
        }

        return null;
    }

    /*
     * 拼接查询志愿者团队SQL
     * */
    private String queryVolunteerTeamSqlBuiler(WxSpiderTeamByPlaceQueryBO queryBO) {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT * FROM wx_spider_volunteer_team WHERE province = '").append(queryBO.getProvince())
                .append("' AND city = '").append(queryBO.getCity())
                .append("' AND district = '").append(queryBO.getDistrict()).append("'");

        if (queryBO.getInstitutionType() == 0) {
            if (queryBO.getEventContentTypeStr() != "" && null != queryBO.getEventContentTypeStr()) {
                sbSql.append(" AND servicetype like '%").append(queryBO.getEventContentTypeStr()).append("%'");
            }
            if (queryBO.getEventContentTypeList() != null && queryBO.getEventContentTypeList().size() > 0) {
                sbSql.append(" AND (");
                queryBO.getEventContentTypeList().forEach(typeItem -> {
                    sbSql.append(" (servicetype like '%").append(typeItem).append("%') OR");
                });
                //截掉最后一个OR
                sbSql.delete(sbSql.length() - 2, sbSql.length());
                sbSql.append(")");
            }
            sbSql.append(" AND unittype != '街道办事处' AND unittype != '医院' AND unittype != '派出所' AND unittype != '卫生服务中心'");
        }
        if (queryBO.getInstitutionType() == 1) {
            sbSql.append(" AND unittype = '街道办事处' AND street = '").append(queryBO.getStreet()).append("'");
        }
        if (queryBO.getInstitutionType() == 2) {
            sbSql.append(" AND ( unittype = '医院' OR unittype = '卫生服务中心' )");
        }
        if (queryBO.getInstitutionType() == 3) {
            sbSql.append(" AND ( unittype = '派出所' OR unittype = '公安局' )");
            if (queryBO.getStreet() != null && queryBO.getStreet() == "" && queryBO.getStreet() != "*") {
                sbSql.append(" AND street = '").append(queryBO.getStreet()).append("'");
            }
        }
        sbSql.append(" ORDER BY ABS ( to_number( longitude, '999.99999999' ) - ").append(queryBO.getLongitude())
                .append(") + ABS ( to_number( latitude, '999.99999999' ) -").append(queryBO.getLatitude())
                .append(") LIMIT 1");

        return sbSql.toString();
    }
}
